package tq.com.tqstudent.ui.activity.classes;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lib.common.base.BaseActivity;
import com.lib.common.utils.SPUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.Subscribe;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import tq.com.tqstudent.App;
import tq.com.tqstudent.R;
import tq.com.tqstudent.adapter.common.CommonAdapter;
import tq.com.tqstudent.adapter.common.MultiItemTypeAdapter;
import tq.com.tqstudent.adapter.common.ViewHolder;
import tq.com.tqstudent.bean.AuthorBean;
import tq.com.tqstudent.bean.BaseBean;
import tq.com.tqstudent.bean.CommentBean;
import tq.com.tqstudent.bean.MalistBean;
import tq.com.tqstudent.bean.ServerBean;
import tq.com.tqstudent.bean.TeacherBean;
import tq.com.tqstudent.bean.UserBean;
import tq.com.tqstudent.bean.UserInfo;
import tq.com.tqstudent.bean.event.ChatEvent;
import tq.com.tqstudent.net.ok.DialogCallback;
import tq.com.tqstudent.net.ok.StringCallback;
import tq.com.tqstudent.net.ok.StringDialogCallback;
import tq.com.tqstudent.ui.activity.HomeActivity;
import tq.com.tqstudent.ui.activity.LoginActivity;
import tq.com.tqstudent.utils.VarietyUtil;

/**
 * @Author rames
 * @date 2019/2/28 17:12
 */
public class MsgActivity extends BaseActivity {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.empty_layout)
    LinearLayout emptyLayout;
    private CommonAdapter adapter;
    private int pageNO = 1;

    public static void show(Activity activity){
        Intent intent = new Intent(activity, MsgActivity.class);
        Bundle bundle = new Bundle();
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    @Override
    public int initLayout() {
        return R.layout.activity_recyclerview;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        setTitle("私信");
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new CommonAdapter<AuthorBean>(this, R.layout.item_activity_msg, new ArrayList()) {
            @Override
            protected void convert(ViewHolder holder, AuthorBean bean, int position) {
                holder.setVisible(R.id.point_iv, bean.unread_count>0);
                if(bean.last_msg != null) {
                    holder.setText(R.id.msg_tv, VarietyUtil.getContentByType(bean.last_msg.content_type, bean.last_msg.content));
                    holder.setText(R.id.time_tv, bean.last_msg.time);
                }

                if(bean.teacher != null) {
                    holder.setText(R.id.name_tv, bean.teacher.name + "(" + VarietyUtil.getSubjectName(bean.teacher.subject) + ")");
                    Glide.with(MsgActivity.this).load(VarietyUtil.getHeadImgUri(bean.teacher.pic)).apply(VarietyUtil.getGlideHeadOptions()).into((ImageView) holder.getView(R.id.head_iv));
                }
            }
        };

        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                AuthorBean bean = (AuthorBean) adapter.getDatas().get(position);
                setReadPoint(bean.teacher.id, false);
                ChatActivity.show(MsgActivity.this, false, bean.teacher.name, bean.teacher.id, 0, position);
            }
        });
        recyclerView.setAdapter(adapter);

        refreshLayout.setOnRefreshListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageNO++;
                getData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNO = 1;
                getData();
            }
        });

        VarietyUtil.setRefreshEnable(refreshLayout, false);
    }

    @Subscribe
    public void onChatBackEvent(ChatEvent event){
        getData();
        /*ArrayList<AuthorBean> list = (ArrayList<AuthorBean>) adapter.getDatas();
        if(list.size() < 1 || list.size() < event.index) return;

        AuthorBean bean = list.get(event.index);
        if(event != null && null != bean){
            AuthorBean.LastMsg lastMsg = bean.last_msg;
            if(null != lastMsg){
                lastMsg.content_type = event.bean.contentType;
                lastMsg.content = event.bean.message;
            }

            adapter.notifyDataSetChanged();
        }*/
    }

    @Override
    public void initData() {
        getData();
    }

    private void getData(){
        String uri = "api/clz/myteacher";
//        OkGo.<BaseBean<List<AuthorBean>>>get(App.getHttpUrl(uri)+ Constants.PAGE_SIZE+"/"+pageNO)
        OkGo.<BaseBean<List<AuthorBean>>>get(App.getHttpUrl(uri))
                .tag(this)
                .execute(new DialogCallback<List<AuthorBean>>(this, false){
                    @Override
                    public void handleSuccess(List<AuthorBean> data) {
                        // 这是加载更多
                        if(refreshLayout.getState() == RefreshState.Loading){
                            adapter.addData(data);
                            refreshLayout.finishLoadMore();

                            // 这是下拉刷新
                        } else {
                            adapter.getDatas().clear();
                            adapter.setData(data);
                            refreshLayout.finishRefresh();
                        }

                        emptyLayout.setVisibility(recyclerView.getAdapter().getItemCount() > 0 ? View.GONE : View.VISIBLE);
                    }

                    @Override
                    public void handleFail(BaseBean body) {
                        super.handleFail(body);
                        refreshLayout.finishLoadMore();
                        refreshLayout.finishRefresh();
                    }
                });
    }

    /**
     * 设置小红点的已读
     * @param targetID
     * @param isGroup 目标类型： 0 表示是目标是普通用户， 1 表示目标是群组
     */
    private void setReadPoint(int targetID, boolean isGroup){
        String uri = "api/im/setread";
        String json = "{\"target_id\""+":"+targetID+",\"score\""+":"+(isGroup?1:0)+"}";
        OkGo.<String>post(App.getHttpUrl(uri))
                .tag(this)
                .upJson(json)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }

                    @Override
                    public void onError(Response<String> response) {

                    }
                });

    }
}
